package com.synjones.handsetS8.ild.pages;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.synjones.handsetS8.R;;
import com.synjones.handsetS8.Utils.util;
import com.synjones.handsetS8.ild.constants.RequestCodes;
import com.synjones.handsetS8.ild.net.api.FileApi;
import com.synjones.handsetS8.ild.net.api.WorkerRegApi;
import com.synjones.handsetS8.ild.net.common.NetCallback;
import com.synjones.handsetS8.ild.net.common.NetResponse;
import com.synjones.handsetS8.ild.net.model.NetResult;
import com.synjones.handsetS8.ild.net.model.UploadImageResult;
import com.synjones.handsetS8.ild.net.model.WorkerRegParam;
import com.synjones.handsetS8.ild.pages.select.SelectActivity;
import com.synjones.handsetS8.ild.utils.BitmapUtil;
import com.synjones.handsetS8.ild.utils.MeasureUtils;
import com.synjones.m1card.M1CardInfo;
import com.synjones.reader.IDCardReaderModule;

import java.io.File;

/**
 * 手动录入
 */
public class ManualInputActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {
    private View root;
    private ImageView ivBack;
    private TextView tvTitle;

    //用工登记参数数据
    private WorkerRegParam workerRegParam = new WorkerRegParam();
    /**
     * 表单控件
     */
    private EditText etWorkerName, etIdCardNo, etWorkerCellPhone;
    private TextView tvUnit, tvTeam, tvWorkType, tvReadBracelet;
    private GridLayout gridFace;
    private ImageView ivFaceAdd;
    private Switch swtTeamManager;
    private Button btnSubmit;
    private LinearLayout llTeamManager;

    //身份证数据
    private String workerName;
    private String idCardNo;
    private String braceletCode;
    private String idCardSidePhoto;
    private String idCardSideEmblem;
    private String faceImageUrl;
    private String localTempImgFileName;
    //分包公司Id，班组Id，工种Id
    private long laborId = -1L, teamId, workTypeId;

    //手环
    IDCardReaderModule idCardReaderModule;
    boolean isConnect;
    final int MESSAGE_FIND_CARD = 0x51;
    boolean findingCard = false;

    //读取手环的弹窗
    private PopupWindow readBraceletWindow;
    //注册成功弹窗
    private PopupWindow registerSuccessWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        root = getLayoutInflater().inflate(R.layout.act_manual_input, null);
        setContentView(root);

        initView();
    }

    /**
     * 控件初始化
     */
    private void initView() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        tvTitle = (TextView) findViewById(R.id.tv_title);

        tvTitle.setText("身份登记");

        ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);

        idCardReaderModule = IDCardReaderModule.getInstance(this);
        isConnect = idCardReaderModule.isOpen();

        initPopWindows();
        //获取传递数据
        Intent intent = getIntent();
        workerName = intent.getStringExtra("worker_name");
        idCardNo = intent.getStringExtra("id_card_no");
        idCardSidePhoto = intent.getStringExtra("id_card_side_photo");
        idCardSideEmblem = intent.getStringExtra("id_card_side_emblem");
        //初始化表单
        initForm();
        fillForm();

    }

    /**
     * 初始化读取手环的弹窗
     */
    private void initPopWindows() {
        //读取手环弹窗
        View readBraceletView = getLayoutInflater().inflate(R.layout.pop_read_bracelet, null);
        readBraceletWindow = new PopupWindow(readBraceletView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        readBraceletWindow.setTouchable(true);
        RelativeLayout bg1 = readBraceletView.findViewById(R.id.rl_read_bracelet_bg);
        bg1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readBraceletWindow.dismiss();
            }
        });

        //登记成功弹窗
        View registerSuccessView = getLayoutInflater().inflate(R.layout.pop_register_success, null);
        registerSuccessWindow = new PopupWindow(registerSuccessView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        registerSuccessWindow.setTouchable(true);
        RelativeLayout bg2 = registerSuccessView.findViewById(R.id.rl_register_success_bg);
        bg2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                registerSuccessWindow.dismiss();
            }
        });
    }

    /**
     * 初始化表单
     */
    private void initForm() {
        //强制竖屏
        if (android.os.Build.VERSION.SDK_INT >= 27) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        }
        etWorkerName = (EditText) findViewById(R.id.et_worker_name);
        etIdCardNo = (EditText) findViewById(R.id.et_id_card_no);
        etWorkerCellPhone = (EditText) findViewById(R.id.et_worker_cellphone);
        tvUnit = (TextView) findViewById(R.id.tv_unit);
        tvTeam = (TextView) findViewById(R.id.tv_team);
        tvWorkType = (TextView) findViewById(R.id.tv_team_name);
        tvReadBracelet = (TextView) findViewById(R.id.tv_read_bracelet);
        gridFace = (GridLayout) findViewById(R.id.grid_face);
        ivFaceAdd = (ImageView) findViewById(R.id.iv_face_add);
        swtTeamManager = (Switch) findViewById(R.id.swt_team_manager);
        btnSubmit = (Button) findViewById(R.id.btn_submit);
        llTeamManager = (LinearLayout) findViewById(R.id.ll_team_manager);

        //设置监听器
        tvUnit.setOnClickListener(this);
        tvTeam.setOnClickListener(this);
        tvWorkType.setOnClickListener(this);
        ivFaceAdd.setOnClickListener(this);
        swtTeamManager.setOnClickListener(this);
        tvReadBracelet.setOnClickListener(this);

        etWorkerName.addTextChangedListener(this);
        etIdCardNo.addTextChangedListener(this);
        etWorkerCellPhone.addTextChangedListener(this);

        btnSubmit.setOnClickListener(this);

    }

    /**
     * 填写表单
     */
    private void fillForm() {
        if (null != workerName) {
            etWorkerName.setText(workerName);
        }
        if (null != idCardNo) {
            etIdCardNo.setText(idCardNo);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                //选择分包单位
                case RequestCodes.SELECT_UNIT:
                    tvUnit.setText(data.getStringExtra("select_item_name"));
                    laborId = data.getLongExtra("select_item_id", 0);
                    break;
                //选择班组
                case RequestCodes.SELECT_TEAM:
                    tvTeam.setText(data.getStringExtra("select_item_name"));
                    teamId = data.getLongExtra("select_item_id", 0);
                    llTeamManager.setVisibility(View.VISIBLE);
                    break;
                //选择工种
                case RequestCodes.SELECT_WORK_TYPE:
                    tvWorkType.setText(data.getStringExtra("select_item_name"));
                    workTypeId = data.getLongExtra("select_item_id", 0);
                    break;
                //人脸照片 todo 目前获取的是缩略图 稍后设计读取原图
                case RequestCodes.FACE_PICTURE:
                    captureFacePicture(data);
                    break;
                //人脸照片剪切
                case RequestCodes.FACE_PICTURE_CUT:
                    cutFacePicture(data);
                    break;
                default:
                    break;
            }
            stepCheckParams();
        }
    }

    /**
     * 拍摄人脸照片之后
     *
     * @param data
     */
    private void captureFacePicture(Intent data) {
        Bundle extras = data.getExtras();
        //获取图片信息
        Bitmap bitmap = (Bitmap) extras.get("data");

        cropPhoto(BitmapUtil.bmpToUri(bitmap));
    }

    private void cutFacePicture(Intent data) {
        String filePath = Environment.getExternalStorageDirectory()
                + "/handset/" + localTempImgFileName;
        File f = new File(filePath);
        ImageView ivFace = new ImageView(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(90, 90);
        layoutParams.width = MeasureUtils.dp2px(90f);
        layoutParams.height = MeasureUtils.dp2px(90f);
        layoutParams.rightMargin = MeasureUtils.dp2px(10f);
        ivFace.setLayoutParams(layoutParams);
        ivFace.setScaleType(ImageView.ScaleType.FIT_XY);

        Toast.makeText(this, f.getAbsolutePath(), Toast.LENGTH_SHORT).show();
        Glide.with(this).load(f).into(ivFace);
        gridFace.addView(ivFace, 0);

        ivFaceAdd.setVisibility(View.GONE);

        //上传图片
        FileApi.uploadImage(filePath, new NetCallback<NetResult<UploadImageResult>>() {
            @Override
            protected void onComplete(NetResponse<NetResult<UploadImageResult>> netResponse) {
                if (netResponse.isSuccess) {
                    faceImageUrl = netResponse.data.getData().getSrc();
                    stepCheckParams();
                }
            }
        });
    }

    /**
     * 拍摄人脸照片之后
     *
     * @param data
     */
    private void cutFacePicture2(Intent data) {
        Bundle extras = data.getExtras();
        //获取图片信息
        Bitmap bitmap = (Bitmap) extras.get("data");
        ImageView ivFace = new ImageView(this);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(90, 90);
        layoutParams.width = MeasureUtils.dp2px(90f);
        layoutParams.height = MeasureUtils.dp2px(90f);
        layoutParams.rightMargin = MeasureUtils.dp2px(10f);
        ivFace.setLayoutParams(layoutParams);
        ivFace.setScaleType(ImageView.ScaleType.FIT_XY);

        ivFace.setImageBitmap(bitmap);

        gridFace.addView(ivFace, 0);
        //上传图片
//        FileApi.uploadImage(file, new NetCallback<NetResult<UploadImageResult>>() {
//            @Override
//            protected void onComplete(NetResponse<NetResult<UploadImageResult>> netResponse) {
//
//            }
//        });

        //保存图片
        //String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmp";

        //不能再添加人脸图片
        ivFaceAdd.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回
            case R.id.iv_back:
                finish();
                break;
            //选择分包单位
            case R.id.tv_unit:
                selectUnit();
                break;
            //选择班组
            case R.id.tv_team:
                selectTeam();
                break;
            //选择工种
            case R.id.tv_team_name:
                selectWorkType();
                break;
            //拍摄人脸照片
            case R.id.iv_face_add:
                getFacePicture();
                break;
            //班组长开关
            case R.id.swt_team_manager:
                break;
            //读取手环
            case R.id.tv_read_bracelet:
                popReadBracelet();
                break;
            //提交
            case R.id.btn_submit:
                submit();
                break;
            default:
                break;
        }
    }

    /**
     * 提交数据
     */
    private void submit() {
        //检查参数
        if (!checkParams()) {
            return;
        }
        //收集有效参数
        workerRegParam.setRealname(etWorkerName.getText().toString());
        workerRegParam.setId_card_no(etIdCardNo.getText().toString());
        workerRegParam.setPhone_no(etWorkerCellPhone.getText().toString());
        workerRegParam.setTeam_id(teamId);
        workerRegParam.setWork_type(workTypeId);
        //workerRegParam.setBracelet_coding(braceletCode);
        workerRegParam.setBracelet_coding("123456");
        workerRegParam.setFace_img(faceImageUrl);
        //workerRegParam.setId_card_img_1();
        //workerRegParam.setId_card_img_2();
        workerRegParam.setIs_manager(swtTeamManager.isChecked() ? 1 : 0);

        WorkerRegApi.reg(workerRegParam, new NetCallback<NetResult>() {
            @Override
            protected void onComplete(NetResponse<NetResult> netResponse) {
                if (netResponse.isSuccess) {
                    Toast.makeText(ManualInputActivity.this, "工人登记成功", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //请求回调成功后弹出弹窗
        registerSuccessWindow.showAtLocation(root, Gravity.CENTER, 0, 0);
    }

    /**
     * 分布采集 检查必要的参数
     */
    private boolean stepCheckParams() {
        btnSubmit.setEnabled(false);
        btnSubmit.setBackgroundColor(Color.parseColor("#CCCCCC"));
        btnSubmit.setTextColor(Color.parseColor("#666666"));

        if ("".equals(etWorkerName.getText().toString().trim())) {
            return false;
        }
        if ("".equals(etIdCardNo.getText().toString().trim())) {
            return false;
        }
        if ("".equals(etWorkerCellPhone.getText().toString().trim())) {
            return false;
        }
        if ("".equals(tvWorkType.getText().toString().trim())) {
            return false;
        }
        if ("".equals(tvUnit.getText().toString().trim())) {
            return false;
        }
        if (null == faceImageUrl) {
            return false;
        }
        Toast.makeText(this, "必要参数已经具备", Toast.LENGTH_SHORT).show();
        btnSubmit.setEnabled(true);
        btnSubmit.setBackgroundColor(Color.parseColor("#009688"));
        btnSubmit.setTextColor(Color.parseColor("#FFFFFF"));

        return true;
    }

    /**
     * 提交前检查参数
     *
     * @return
     */
    private boolean checkParams() {
        btnSubmit.setEnabled(false);
        btnSubmit.setBackgroundColor(Color.parseColor("#CCCCCC"));
        btnSubmit.setTextColor(Color.parseColor("#666666"));

        if ("".equals(etWorkerName.getText().toString().trim())) {
            Toast.makeText(this, "请输入工人姓名", Toast.LENGTH_SHORT).show();
            return false;
        }
        if ("".equals(etIdCardNo.getText().toString().trim())) {
            Toast.makeText(this, "请输入身份证号码", Toast.LENGTH_SHORT).show();
            return false;
        }
        if ("".equals(etWorkerCellPhone.getText().toString().trim())) {
            Toast.makeText(this, "请输入工人手机", Toast.LENGTH_SHORT).show();
            return false;
        }
        if ("".equals(tvWorkType.getText().toString().trim())) {
            Toast.makeText(this, "请选择工种", Toast.LENGTH_SHORT).show();
            return false;
        }
        if ("".equals(tvUnit.getText().toString().trim())) {
            Toast.makeText(this, "请选择分包单位", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (null == faceImageUrl) {
            Toast.makeText(this, "请拍摄人脸照片", Toast.LENGTH_SHORT).show();
            return false;
        }

        btnSubmit.setEnabled(true);
        btnSubmit.setBackgroundColor(Color.parseColor("#009688"));
        btnSubmit.setTextColor(Color.parseColor("#FFFFFF"));

        return true;
    }

    /**
     * 弹出读取手环的窗口
     */
    private void popReadBracelet() {
        readBraceletWindow.showAtLocation(root, Gravity.CENTER, 0, 0);
        //开始寻卡
        FindCard(5000);
    }

    /**
     * 选择分包单位
     */
    private void selectUnit() {
        toSelect("选择分包单位", RequestCodes.SELECT_UNIT, 0);
    }

    /**
     * 选择班组
     */
    private void selectTeam() {
        if (laborId == -1) {
            Toast.makeText(this, "你必须要先选择一个分包单位", Toast.LENGTH_SHORT).show();
            return;
        }
        toSelect("选择班组", RequestCodes.SELECT_TEAM, 1);
    }

    /**
     * 选择工种
     */
    private void selectWorkType() {
        toSelect("选择工种", RequestCodes.SELECT_WORK_TYPE, 2);
    }

    /**
     * 到选择页面
     *
     * @param title
     * @param requestCode
     */
    private void toSelect(String title, int requestCode, int dataType) {
        Intent intent = new Intent(this, SelectActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("data_type", dataType);
        if (dataType == 1) {
            intent.putExtra("labor_id", laborId);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 拍摄人脸
     */
    private void getFacePicture() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, RequestCodes.FACE_PICTURE);
    }

    /**
     * 读取手环的结果
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (MESSAGE_FIND_CARD == msg.what) {
                // beep();
                //Toast.makeText(activity, "find a Card", Toast.LENGTH_SHORT).show();
                M1CardInfo m1CardInfo = (M1CardInfo) msg.obj;
                if (m1CardInfo != null) {
                    braceletCode = m1CardInfo.getCardNoStr();
                    tvReadBracelet.setText(braceletCode);
                    Toast.makeText(ManualInputActivity.this, "已探测到手环", Toast.LENGTH_SHORT).show();
                    readBraceletWindow.dismiss();
                }
            }
        }
    };

    /**
     * 寻卡
     */
    public void FindCard(final int timeout) {
        findingCard = true;
        new Thread(new Runnable() {

            @Override
            public void run() {
                M1CardInfo m1CardInfo = null;
                long t = System.currentTimeMillis();
                while (findingCard && System.currentTimeMillis() - t < timeout && m1CardInfo == null) {
                    m1CardInfo = idCardReaderModule.findM1Card();
                    if (m1CardInfo != null) {
                        mHandler.obtainMessage(MESSAGE_FIND_CARD, m1CardInfo).sendToTarget();
                        break;
                    }
                    util.sleep(50);
                }
                findingCard = false;
                if (m1CardInfo == null)
                    mHandler.obtainMessage(MESSAGE_FIND_CARD, null).sendToTarget();

            }
        }).start();
    }

    /**
     * 裁剪图片
     */
    private void cropPhoto(Uri uri) {
        File dir = new File(Environment.getExternalStorageDirectory() + "/handset/");
        if (!dir.exists()) dir.mkdirs();
        long localTempImg = System.currentTimeMillis();
        localTempImgFileName = localTempImg + ".jpg";
        File f = new File(dir, localTempImgFileName);
        Uri u = Uri.fromFile(f);

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, u);//存储
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RequestCodes.FACE_PICTURE_CUT);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        stepCheckParams();
    }
}